﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using Microsoft.Practices.Unity;
using System.Reflection;
using System.Configuration;
using Microsoft.Practices.Unity.Configuration;
using System.ServiceModel;
using System.Data.SqlClient;
using Microsoft.Synchronization;
using Microsoft.Synchronization.Data.SqlServer;
using Microsoft.Synchronization.Data;
using System.IO;
namespace SkynetConsole
{
    class Program
    {
        static IUnityContainer ContainerService   = new UnityContainer();  
        public static void LoadConfiguration()
        {
            var fileMapPolicies = new ExeConfigurationFileMap { ExeConfigFilename = @".\Config\Aspect.config" };
            var configurationPolicies = ConfigurationManager.OpenMappedExeConfiguration(fileMapPolicies, ConfigurationUserLevel.None);
            var unitySectionPolicies = (UnityConfigurationSection)configurationPolicies.GetSection("unity");
            ContainerService.LoadConfiguration(unitySectionPolicies);


            var fileMapDataAccess = new ExeConfigurationFileMap { ExeConfigFilename = @".\Config\DataAccess.config" };
            var configurationDataAccess = ConfigurationManager.OpenMappedExeConfiguration(fileMapDataAccess, ConfigurationUserLevel.None);
            var unitySectionDataAccess = (UnityConfigurationSection)configurationDataAccess.GetSection("unity");
            ContainerService.LoadConfiguration(unitySectionDataAccess);

            var fileMapBusiness = new ExeConfigurationFileMap { ExeConfigFilename = @".\Config\Business.config" };
            var configurationBusiness = ConfigurationManager.OpenMappedExeConfiguration(fileMapBusiness, ConfigurationUserLevel.None);
            var unitySectionBusiness = (UnityConfigurationSection)configurationBusiness.GetSection("unity");
            ContainerService.LoadConfiguration(unitySectionBusiness);
        }

        delegate bool EnumWindowsCallback(IntPtr hWnd, IntPtr lParam);

        delegate void DoOperationCallBack(double result);

        //dumpbin
        [DllImport("Skynet.WinApi.dll", CallingConvention = CallingConvention.ThisCall)]
        static extern void DoOperation(double input, StringBuilder operation, MulticastDelegate callback);


        [DllImport("user32.dll")]
        static extern int EnumWindows(EnumWindowsCallback hWnd, IntPtr lParam);

        static bool PrintWindow(IntPtr hWnd, IntPtr lParam)
        {
            Console.WriteLine(hWnd.ToInt64());
            return true;
        }

        static void PrintResult(double result)
        {
            Console.WriteLine(result.ToString());
        }

        public static void AuditObject(object arg)
        {
            var typ = arg.GetType();
            var att = Attribute.GetCustomAttribute(typ, typeof(Infrastructure.Aspect.Metadata.AuditAttribute)) as Infrastructure.Aspect.Metadata.AuditAttribute;
            if (att != null)
            {
                switch (att.Level)
                {
                    case Infrastructure.Aspect.Metadata.AuditLevel.High:
                        Console.WriteLine("Utilizacion de  " +  typ.Name);
                        break;
                    case Infrastructure.Aspect.Metadata.AuditLevel.Low:

                        break;
                    default:
                        break;
                }
            }

        }

        [STAThread]
        static void Main(string[] args)
        {
            LoadConfiguration();
            //var motor = ContainerService.Resolve<IMotor>();
            //motor.Acelerar(); 


            //Console.WriteLine("Cliente");
            //Console.ReadLine();

            //try
            //{

            //    //basicTransportCredentialBasic
            //    //basicTransportCredentialOnlyWindows
            //    //wsTransportWindows
            //    var proxy = new Skynet.ServiceProxies.SkynetLibraryServiceProxy("wsTransportWindows");

            //    proxy.ClientCredentials.Windows.ClientCredential.UserName = "Developer2";
            //    proxy.ClientCredentials.Windows.ClientCredential.Password = "Pa$$w0rd";

            //    var request = new Skynet.ServiceContracts.MessageContracts.FindCategoryRequest();
            //    request.Operation = Skynet.ServiceContracts.DataContracts.DCExamFindCategoryOperation.FindAll;
            //    var response = proxy.FindExamCategories(request);
            //    var items = response.ExamCategories;
            //    foreach (var item in items)
            //    {
            //        Console.WriteLine(item.Title);
            //    }
            //}
            //catch (FaultException ex)
            //{

            //    Console.WriteLine(ex.Message);
            //}
            //catch (Exception ex)
            //{
            //    Console.WriteLine(ex.Message);
            //}

            //Console.ReadLine();


            

            //LoadConfiguration();
            //Console.WriteLine(System.Security.Principal.WindowsIdentity.GetCurrent().Name);


            //var con = new System.Data.SqlServerCe.SqlCeConnection(@"Data Source=|DataDirectory|\accessibility.sdf;Max Database Size=2047");
            //var cmd = new System.Data.SqlServerCe.SqlCeCommand("insert into Accessibility( id, [application], [userid], code) values( NEWID(), 'test', NEWID(), 'client')", con);
            //con.Open();

            //cmd.ExecuteNonQuery();

            //con.Close();


            SqlConnection clientConn = new SqlConnection(@"Data Source=skynetlibrary;Initial Catalog=SkyNetLibrary2;Integrated Security=True;MultipleActiveResultSets=True;");

            
           SqlConnection serverConn = new SqlConnection("Data Source=skynetlibrary;Initial Catalog=SkyNetLibrary;Integrated Security=True;MultipleActiveResultSets=True;");





            //DbSyncScopeDescription scopeDesc = new DbSyncScopeDescription("Skynet");
            //DbSyncTableDescription customerDescription = SqlSyncDescriptionBuilder.GetDescriptionForTable("Accessibility", serverConn);

            //scopeDesc.Tables.Add(customerDescription);

            //SqlSyncScopeProvisioning serverConfig = new SqlSyncScopeProvisioning(serverConn);
            //serverConfig.PopulateFromScopeDescription(scopeDesc);
            //serverConfig.SetCreateTableDefault(DbSyncCreationOption.CreateOrUseExisting);
            //serverConfig.ObjectSchema = "Sync";
            //serverConfig.Apply();


            //File.WriteAllText("SampleConfigScript.txt", serverConfig.Script());

            //DbSyncScopeDescription clientSqlDesc = SqlSyncDescriptionBuilder.GetDescriptionForScope("Skynet", null, "Sync", serverConn);
            //SqlSyncScopeProvisioning clientSqlConfig = new SqlSyncScopeProvisioning(clientConn, clientSqlDesc);
            //clientSqlConfig.SetCreateTableDefault(DbSyncCreationOption.CreateOrUseExisting);
            //clientSqlConfig.ObjectSchema = "Sync";
            //clientSqlConfig.Apply();

            //File.WriteAllText("SampleConfigScriptClient.txt", clientSqlConfig.Script());

           //SyncOrchestrator or = new SyncOrchestrator();
           //var con = ConfigurationManager.ConnectionStrings["SkynetLibrary"].ConnectionString;           
           //or.LocalProvider = new Infrastructure.WpfClient.Accessibility.AccessibilityCacheServerSyncProvider(con);
           //or.RemoteProvider = new SqlSyncProvider("Skynet", serverConn, null, "Sync");

           //or.Direction = SyncDirectionOrder.Download;
           //var sta = or.Synchronize();

           //Console.WriteLine("Start Time: " + sta.SyncStartTime);
           //Console.WriteLine("Total Changes Uploaded: " + sta.UploadChangesTotal);
           //Console.WriteLine("Total Changes Downloaded: " + sta.DownloadChangesTotal);
           //Console.WriteLine("Complete Time: " + sta.SyncEndTime);
           //Console.WriteLine(String.Empty);


            





            
            

            
            //agent.LocalProvider = new Infrastructure.WpfClient.Accessibility.AccessibilityCacheClientSyncProvider( @"Data Source=|DataDirectory|\accessibility.sdf;Max Database Size=2047");            

            

    //        var localcon = new SqlConnection(ConfigurationManager.ConnectionStrings["localsync"].ConnectionString);

  //          agent.LocalProvider = new Infrastructure.WpfClient.Accessibility.AccessibilityCacheClientSyncProvider(ConfigurationManager.ConnectionStrings["localsync"].ConnectionString);








            

           var agent = new Infrastructure.WpfClient.Accessibility.AccessibilityDataCacheSyncAgent();


           agent.Accssebility.CreationOption = TableCreationOption.TruncateExistingOrCreateNewTable;
           agent.Accssebility.SyncDirection = Microsoft.Synchronization.Data.SyncDirection.DownloadOnly;

            var con = ConfigurationManager.ConnectionStrings["SkynetLibrary"].ConnectionString;
            agent.RemoteProvider =  new Microsoft.Synchronization.Data.ServerSyncProviderProxy(new Infrastructure.WpfClient.Accessibility.AccessibilityDataCacheSyncServiceClient());
            //agent.RemoteProvider = new Infrastructure.WpfClient.Accessibility.AccessibilityCacheServerSyncProvider(con);



            agent.LocalProvider = new Infrastructure.WpfClient.Accessibility.AccesibilitySQLClientProvider();


            //SqlConnection clientConn = new SqlConnection(@"Data Source=skynetlibrary;Initial Catalog=SkyNetLibrary2;Integrated Security=True;MultipleActiveResultSets=True;");
//            agent.LocalProvider = new Infrastructure.WpfClient.Accessibility.AccessibilityCacheServerSyncProvider(@"Data Source=skynetlibrary;Initial Catalog=SkyNetLibrary2;Integrated Security=True;MultipleActiveResultSets=True;");

            


            agent.Configuration.SyncParameters.Add(new Microsoft.Synchronization.Data.SyncParameter("@CurrentUserId",  new Guid("7E8B3987-75C9-45DB-AB76-D0B4FEA3E9B3")));

            
            var stat = agent.Synchronize();

            Console.WriteLine(string.Format(" total TotalChangesDownloaded download {0}", stat.TotalChangesDownloaded.ToString()));
            Console.WriteLine(string.Format(" total TotalChangesUploaded {0}", stat.TotalChangesUploaded.ToString()));
            Console.WriteLine(string.Format(" total DownloadChangesApplied {0}", stat.DownloadChangesApplied.ToString()));
            Console.WriteLine(string.Format(" total DownloadChangesFailed {0}", stat.DownloadChangesFailed.ToString()));
            Console.WriteLine(string.Format(" total UploadChangesApplied {0}", stat.UploadChangesApplied.ToString()));
            Console.WriteLine(string.Format(" total UploadChangesFailed {0}", stat.UploadChangesFailed.ToString()));






            //con.Open();
            //cmd.CommandText = "select * from Accessibility";

            //var reader = cmd.ExecuteReader();
            //var tb = reader.GetSchemaTable();
            //while (reader.Read())
            //{
            //    Console.WriteLine(reader["code"].ToString());
            //}
            //con.Close();

            //var s =  ContainerService.Resolve< Infrastructure.Aspect.Accessibility.AccessibilityService>();

            //var id = Guid.NewGuid();

            //s.setSetting<string>("apptest", id, "one", "onevalue");

            //var r1 = s.getSetting<string>("apptest", id, "one", "nada");

            //s.setSetting<string>("apptest", id, "one", "two", "twovalue");


            //var r2 = s.getSetting<string>("apptest", id, "one", "two","nada");

            //s.setSetting<string>("apptest", id, "one", "two", "three", "threevalue");

            //var r3 = s.getSetting<string>("apptest", id, "one", "two", "three", "nada");
            
            

            



            //var pro = new SKLCon.SkynetLibraryServiceClient("NetTcpBinding_ISkynetLibraryService");
            //try
            //{

            //    var response = pro.GetStatus(new SKLCon.GetStatusRequest() { });
            //    Console.WriteLine(response.GetStatusResult);

            //    response = pro.GetStatus(new SKLCon.GetStatusRequest() { });
            //    Console.WriteLine(response.GetStatusResult);
            //}
            
            //catch (System.ServiceModel.FaultException ex)
            //{
            //    Console.WriteLine(ex.Reason);
            //}
            //catch (Exception ex)
            //{

            //    Console.WriteLine(ex.Message);
            //}

            //try
            //{
             
            //    var response = pro.GetStatus(new SKLCon.GetStatusRequest() { });
            //    Console.WriteLine(response.GetStatusResult);
            //}
            //catch (System.ServiceModel.FaultException<SKLCon.SkynetServiceFault> ex)
            //{
                
            //    Console.WriteLine(ex.Detail.UserMessage);
            //}
            //catch (System.ServiceModel.FaultException ex)
            //{
                

            //    Console.WriteLine(ex.Reason);
            //}
            //catch (Exception ex)
            //{
            //    Console.WriteLine(ex.Message);
            //}

            




//            var csp = new SKLIISProxy.SkynetSecurityTestClient();
  //          csp.ClientCredentials.Windows.ClientCredential = new System.Net.NetworkCredential("Developer2", "Pa$$w0rd");
            //csp.ClientCredentials.UserName.UserName = "Developer2";
            //csp.ClientCredentials.UserName.Password = "Pa$$w0rd";
    //        var res  =  csp.GetStatus("test");
      //      Console.WriteLine(res);
            
            //var id = Guid.NewGuid();
            //Console.WriteLine("Session Id  " + id.ToString());
            //System.Diagnostics.Trace.CorrelationManager.ActivityId = id; 


            //SKLCon.SkynetLibraryServiceClient cl = new SKLCon.SkynetLibraryServiceClient("WSHttpBinding_ISkynetLibraryService"); 
            //var req  =  new SKLCon.FindCategoryRequest();
            //var res =  cl.FindExamCategories(req);

            //foreach (var item in res.ExamCategories)
            //{
            //    Console.WriteLine(item.Title);                
            //}

            




            





            //using (var scope = new System.Transactions.TransactionScope())
            //{
            //   var proxy = new SKLTranProxy.SkynetLibraryTransactionServiceClient();
            //    SKLTranProxy.MaintenanceCustomerRequest req = new SKLTranProxy.MaintenanceCustomerRequest();
            //    req.Customer = new Skynet.BusinessEntities.Customer();
            //    req.Customer.Id = Guid.Parse("FEE7B691-C072-452C-9712-7CF1AC86BB3A");
            //    req.Customer.Name = "Test";
            //    req.Customer.LastName = "Test";

            //    proxy.MaintenanceCustomer(req);

            //    SKSTranProxy.SkySchoolTransactionServiceClient proxy2 = new SKSTranProxy.SkySchoolTransactionServiceClient();
            //    SKSTranProxy.MaintenanceStudentRequest req2 = new SKSTranProxy.MaintenanceStudentRequest();
            //    req2.Student = new Skynet.BusinessEntities.Student();
            //    req2.Student.Id = req.Customer.Id;
            //    req2.Student.Name = req.Customer.Name;
            //    req2.Student.LastName = req.Customer.LastName;
            //    req2.Student.Code = "NOT SPECIFIED";
            //    proxy2.MaintenanceStudent(req2);

            //    scope.Complete();
            //}


            


            //LoadConfiguration();


            



            ////var MotorType = System.Configuration.ConfigurationManager.AppSettings["MotorProvider"];
            ////var target = Type.GetType(MotorType);
            ////IMotor  mt = Activator.CreateInstance(target) as IMotor;  
            //IMotor mt = ContainerService.Resolve<IMotor>();  

            


            //mt.Acelerar();
            //mt.Acelerar();
            //mt.Acelerar();
            //mt.Acelerar();


            //var proxy = new TestProxy.SkynetLibraryServiceClient();
            
            //TestProxy.MaintenanceExamCategoryRequest req = new TestProxy.MaintenanceExamCategoryRequest();
            
            //proxy.MaintenanceExamCategory(req); 
            





            //var exa = new Skynet.BusinessEntities.Exam();
            //exa.Id = Guid.NewGuid();
            //exa.Title = "exam 70536";

            //var cat = new Skynet.BusinessEntities.ExamCategory();
            //cat.Id = Guid.NewGuid();
            //cat.Title = "Certification";


            //AuditObject(exa);
            //AuditObject(cat);  


            //var asm = Assembly.Load("Skynet.BusinessEntities");
            //var types = asm.GetTypes();
            //foreach (var item in types)
            //{
            //    Console.WriteLine("=============");
            //    Console.WriteLine(item.Name);
            //    foreach (var mem in item.GetMembers())
            //    {
            //        Console.WriteLine(mem.Name);                   
            //    }
            //    Console.WriteLine("=============");                
            //}


            

           // EnumWindows(PrintWindow, IntPtr.Zero);
            //StringBuilder sb =  new StringBuilder("potencia");
            //DoOperationCallBack cb = new DoOperationCallBack(PrintResult);
            //for (double i = 0; i < 200; i=i+3)
            //{
            //    DoOperation(i, sb, cb);                    
            //}            

            //var ex = Skynet.Office.ExcelUtility.CreateExcel("myexcel.xlsx");
            //Skynet.Office.ExcelUtility.ReleaseExcel(ex);

            //var media = new Skynet.Office.Media.MediaView();
            ////media.ShowDialog();
            //Type excelType = Type.GetTypeFromProgID("Excel.Application");
            //dynamic x1 = Activator.CreateInstance(excelType);
            //x1.Visible = true;
            //excelType.InvokeMember(
            //    "Visible", BindingFlags.SetProperty,
            //     null, xl, new object[] { true });


            

            Console.ReadLine();
        }
    }
    public interface IMotor
    {
        void Acelerar();
    }
    public class Toyota : IMotor
    {

        public void Acelerar()
        {
            Random r = new Random();
            System.Threading.Thread.Sleep(r.Next( 1000,  4000));
            Console.WriteLine("motor toyota acelerando");
        }
    }

    public class Volkswagen : IMotor
    {
        public void Acelerar()
        {
            Random r = new Random();
            System.Threading.Thread.Sleep(r.Next(1000, 4000));
            Console.WriteLine("motor volkswagen acelerando");
        }
    }
}
